package com.css.fxfzdzzh.modules.basicData.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.modules.basicData.entity.Climate;
import com.css.fxfzdzzh.modules.basicData.landslideSite.entity.LandslideSiteFileData;
import com.css.fxfzdzzh.modules.basicData.param.ClimateParam;
import com.css.fxfzdzzh.modules.basicData.repository.impl.ClimateRepository;
import com.css.fxfzdzzh.modules.drill.service.DrillService;
import com.css.fxfzdzzh.util.PlatformDateUtils;
import com.css.fxfzdzzh.util.PlatformObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Dbj
 * @date 2023年03月01日  13:40
 */
@Service
public class ClimateService {

    @Resource
    private ClimateRepository climateRepository;

    @Resource
    private DrillService drillService;

    @Value("${basicData.url}")
    public String basicDataUrl;

    public RestResponse page(ClimateParam param) {
        String url = basicDataUrl + "/datacenter/jcClimate/page?1=1";
        Map<String, Object> map = JSON.parseObject(JSONObject.toJSONString(param), Map.class);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null) {
                url = url + "&" + entry.getKey() + "=" + entry.getValue();
            }
        }
        RestResponse jcsj = drillService.getJCSJ(url, 2);
        return jcsj;
    }

    public void exportExcel(HttpServletResponse response, ClimateParam param) throws Exception{
        String url = basicDataUrl + "/test/dictItems/tree?province="+param.getProvince()+"&city="+param.getCity()
                +"&county="+param.getCounty();
        RestResponse restResponse = drillService.getJCSJ(url, 3);
        JSONObject json = (JSONObject) JSON.toJSON(restResponse.getData());
        List<JSONObject> list = (List<JSONObject>)json.get("data");
//        JSONArray data =(JSONArray) restResponse.getData();
//        List<JSONObject> list = JSONObject.parseArray(data.toJSONString(),JSONObject.class);
        if (list == null || list.size() <= 0) {
            throw new RuntimeException("数据为空,无法导出！");
        }
        List<Climate> climates = new ArrayList<>();
        if(PlatformObjectUtils.isNotEmpty(list)){
            list.forEach(jsonObject->{
                Climate climate = JSONObject.toJavaObject(jsonObject, Climate.class);
                climates.add(climate);
            });
        }
        climateRepository.exportExcel(climates,response);
    }
}
